package club.babyf.nativeai.demo.algorithm;

/**
 * _20_Divided.
 *
 * @author zhanglei.
 * @date 2025/7/20 19:07.
 * @description 两数相除.
 */
public class _20_Divided {

    public int divided(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;
        }

        int sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1;

        if (dividend > 0) dividend = -dividend;
        if (divisor > 0) divisor = -divisor;

        int quo = 0;
        while (dividend <= divisor) {
            int temp = divisor;
            int mul = 1;
            while (temp >= (Integer.MIN_VALUE >> 1) && temp + temp >= dividend) {
                temp += temp;
                mul += mul;
            }
            dividend -= temp;
            quo += mul;
        }

        return sign == 1 ? quo : -quo;
    }

    public static void main(String[] args) {
        _20_Divided divided = new _20_Divided();
        int divided_1 = divided.divided(10, 3);
        System.out.println(divided_1);

        int divided_2 = divided.divided(-7, 3);
        System.out.println(divided_2);
    }

}
